_collections.py 743 B

123456789101112131415161718192021222324252627282930
  1. import collections
  2. # from jaraco.collections 3.3
  3. class FreezableDefaultDict(collections.defaultdict):
  4. """
  5. Often it is desirable to prevent the mutation of
  6. a default dict after its initial construction, such
  7. as to prevent mutation during iteration.
  8. >>> dd = FreezableDefaultDict(list)
  9. >>> dd[0].append('1')
  10. >>> dd.freeze()
  11. >>> dd[1]
  12. []
  13. >>> len(dd)
  14. 1
  15. """
  16. def __missing__(self, key):
  17. return getattr(self, '_frozen', super().__missing__)(key)
  18. def freeze(self):
  19. self._frozen = lambda key: self.default_factory()
  20. class Pair(collections.namedtuple('Pair', 'name value')):
  21. @classmethod
  22. def parse(cls, text):
  23. return cls(*map(str.strip, text.split("=", 1)))